
package westh.ilib.struts.action.croDomainSearch;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.net.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import westh.ilib.bean.croDomainSearch.Author;
import westh.ilib.bean.croDomainSearch.Resource;
import westh.ilib.service.ResourceService;
import westh.ilib.util.PageInfo;

import java.net.InetSocketAddress;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.MemcachedClient;
import westh.config.Config;
//import westh.ilib.bean.croDomainSearch.Resource;

public class GetKeyWordResultAction extends Action {
	private final static Log log = LogFactory.getLog(GetKeyWordResultAction.class);
	private static MemcachedClient c = null;
	//get clouds Ip address
	String localhostUrl = Config.get("localhostUrl");
	String remoteUrl = Config.get("remoteUrl");

	public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) 
	throws Exception{
		//得到输入的Json-串
		
		DynaActionForm f = (DynaActionForm) form;
		
		//we must get some information from the request: type, field, inputStr, pageNo, pageSize

		String[] type= {"2","3"};
		
		String[] field={"2","5"};	
		
		String query=request.getParameter("inputStr");
	
		log.debug("^^^^^^^^^^^^^^^^^^^^^^ inputStr="+query);
		
		//String ipAddress = request.getRemoteAddr();
		
        String strPageNo = "0";
        
        String strPageSize = "0";

		//String ipAddress = request.getRemoteAddr();
		
		// dispatch page related begin
       
        
       
        // dispatch page related end
        
        log.debug("strPagesize="+strPageSize);
        
		/*String uId=request.getRemoteUser();
		
		if(uId==null)
		{
			uId="WTF";
		}
		
		log.debug("uid="+uId);*/
		
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String queryTimeString = tempDate.format(new java.util.Date());

		
		ResourceService rscService=new ResourceService();
		
		
		//getResourcelistBy query begin
		JSONObject resultObject=new JSONObject();
		resultObject.put("query", query);
		
		
		JSONArray rscTypeList=new JSONArray();

		for(int i=0;i<type.length;i++)
		{
			rscTypeList.add(type[i]);
			
		}
		
		resultObject.put("rscTypeList", rscTypeList.toString());
		
		JSONArray rscFieldList=new JSONArray();
		
		for(int i=0;i<field.length;i++){
			rscFieldList.add(field[i]);
		}
		
		resultObject.put("rscFieldList", rscFieldList.toString());
		
		String resultObjectJson=resultObject.toString();
		
		log.debug("resultObjectJson="+resultObjectJson);
		
		//save query log begin
		
		//String saveLogRetCode=rscService.saveQueryLog(request, uId, query, queryTimeString, rscTypeList, rscFieldList, ipAddress, log);
		//log.debug("saveLogRetCode="+saveLogRetCode);
		
		//save query log end
		
		
		JSONObject inJson = new JSONObject();
		
		String methodName = "getQueryResult";
		inJson.put("methodName", methodName);
		inJson.put("jsonStr", resultObject);
		
		String inputStr=inJson.toString();
		
		//
		log.debug(inputStr);
		
		String outString = "";
		//outString = rscService.getResouceListByJson(inputStr, log);
		//For Debug
		try{
			if (c == null)
				c = new MemcachedClient(new InetSocketAddress(remoteUrl, 12000));
			c.flush();
		//outString=rscService.getResouceListByJson("{\"query\":\"how to read a paper\",\"rscTypeList\":[\"1\",\"2\"],\"rscFieldList\":[\"2\",\"5\"]}",log);
			String strQuery = URLEncoder.encode(query);
			log.debug("encode: " + strQuery);
			outString = (String)c.get(strQuery);
			//c.delete("how to read a paper");
			if (outString== null)
			{
				log.debug("COW then");
				outString=rscService.getResouceListByJsonMul(resultObjectJson,log);
				//log.debug(outString);
				c.set(strQuery, 3600, outString);
			}
			else
			{
				log.debug("COW else");
				//log.debug(outString);
			}
			//outString=rscService.getResouceListByJson(resultObjectJson,log);
			//outString=rscService.getResouceListByJsonMul(resultObjectJson,log);
			//c.set("key", 3600, outString);
			//

		}catch(Exception e){
			e.printStackTrace();
			outString=rscService.getResouceListByJsonMul(resultObjectJson,log);
			log.debug("COW try ok");
		}
		//log.debug("outString COW="+outString);
		log.debug("Finished getting resources.");
		request.setAttribute("outString", outString);
		//System.out.println(outString);
		//log.debug("outString = "+outString);	
		String retCode=""; //返回代码
		String retMsg="";//返回结果信息
		String returnStr="fail";//跳转信息
		
		JSONObject jsonOut= JSONObject.fromObject(outString);
		retCode = jsonOut.getString("retCode");
		
		if (retCode.equals("4501")) 
		{
			String result = jsonOut.getString("result");
			
			JSONArray resultArry = JSONArray.fromObject(result);
			log.info("JSONArray=" + resultArry.size());
			System.out.println("JSONArray=" + resultArry.size());
			//解析数组
			
			List<Resource> list = new ArrayList<Resource>();
			for(int i=0;i<resultArry.size();i++){
				Resource  resource = new Resource();
				JSONObject jsonOut2 = JSONObject.fromObject(resultArry.get(i));
				resource.setRscId(jsonOut2.getString("rscId"));
				resource.setRscTitle(jsonOut2.getString("rscTitle"));
				String firstAuthorJson=jsonOut2.getString("rscFirstAuthor");
				if(!firstAuthorJson.equals("")){
					Author author1=new Author();
					JSONObject firstAuthor=JSONObject.fromObject(firstAuthorJson);
					author1.setUid(firstAuthor.getString("uid"));
					author1.setName(firstAuthor.getString("name"));
				//author1.setIeeeRefid(firstAuthorJson.getString("ieeeRefid"));
				//author1.setInstitution(firstAuthorJson.getString("institution"));
					resource.setRscFirstAuthor(author1);
				}
				resource.setRscAbstract(jsonOut2.getString("rscAbstract"));
				resource.setRscPublishDate(jsonOut2.getString("rscPublishDate"));
				resource.setRscField(Integer.parseInt(jsonOut2.getString("rscField")));
				//System.out.println(jsonOut2);
				//resource.setResourceId(jsonOut2.getString("resourceId"));
				//resource.setResourceTitle(jsonOut2.getString("resourceTitle"));
				//resource.setResourceSummary(jsonOut2.getString("resourceSummary"));
				//resource.setResourcePublishDate(jsonOut2.getString("resourcePublishDate"));
				//resource.setResourceFirstAuthor(jsonOut2.getString("resourceAuthor"));
				resource.setRscType(Integer.parseInt(jsonOut2.getString("rscType")));
				//resource.setField(jsonOut2.getString("field"));
				//request.setAttribute("resource", resource);
				list.add(resource);
				//break;
			}
			/****************解析输出jSon串   end*********************/
			
			//request.setAttribute("list", list);
			
			
			/**dispatch page related 
			 * begin*/
			PageInfo pageInfo = new PageInfo();
			int iPageNo = pageInfo.getPageNoFromJSP(strPageNo);
			int iPageSize = pageInfo.getPageSizeFromJSP(strPageSize);
			
			
            pageInfo.setMaxCount(list.size());
            pageInfo.setPageNO(iPageNo);
            pageInfo.setPageSize(iPageSize);
            
            List outputList=null;
            
            int endCount=pageInfo.getMaxCount();
            
            if(endCount>iPageSize*iPageNo)
            {
            	endCount=iPageSize*iPageNo;
            	outputList=list.subList(iPageSize * (iPageNo - 1), endCount);
            }
            else if(endCount<iPageSize*iPageNo&&endCount>iPageSize * (iPageNo - 1))
            {
            	outputList=list.subList(iPageSize * (iPageNo - 1), endCount);
            }
            else
            {
            	iPageNo=pageInfo.getMaxCount()/iPageSize + 1;
            	pageInfo.setPageNO(iPageNo);
            	if(endCount>iPageSize*iPageNo)
            		endCount=iPageSize*iPageNo;
            	outputList=list.subList(iPageSize * (iPageNo - 1), endCount);
            }
            	
            //List outputList=list.subList(iPageSize * (iPageNo - 1), endCount);

            pageInfo.setPageList(outputList);

            request.setAttribute("pageInfo", pageInfo);
			/**dispatch page related 
			 * end*/
			
			log.debug("at last: query="+query);
			request.setAttribute("inputStr", query);
			request.setAttribute("rscTypeList", rscTypeList);
			request.setAttribute("rscFieldList", rscFieldList);
			
			log.debug("at the end of the GetQueryResultAction!");
			log.debug("rscFieldList(field)="+rscFieldList.toString());
			log.debug("rscTypeList(type)="+rscTypeList.toString());
			log.debug("strPageNo="+strPageNo);
			log.debug("strPageSize="+strPageSize);

			
			returnStr = "succ";

		}
		if (retCode.equals("4502")) {
			retMsg = jsonOut.getString("retMsg");
			request.setAttribute("info", retMsg);
			
			returnStr = "fail";
		}
		return mapping.findForward(returnStr);
	}

}






